package com.boomsecret.juc.executor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjinliang on 2019/1/22.
 */
public class ExecutorServiceDemo04 {
    private static ExecutorService threadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

    public static void main(String[] args) {
        Callable<String> callable01 = () -> {
            System.out.println("callback01 start.");
            TimeUnit.SECONDS.sleep(3);
            System.out.println("callback01 end.");
            return "01 response";
        };

        Callable<String> callable02 = () -> {
            System.out.println("callable02 start.");
            TimeUnit.SECONDS.sleep(3);
            System.out.println("callable02 end.");
            return "02 response";
        };

        List<Callable<String>> tasks = new ArrayList<>();
        tasks.add(callable01);
        tasks.add(callable02);

        try {
            System.out.println("invokeAny start");
            String result = threadPool.invokeAny(tasks);
            System.out.println("invokeAny end");
            System.out.println("response:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        threadPool.shutdown();
        System.out.println("主程序结束");
    }
}
